"""
处理待处理的订单 - 临时解决方案
直接将订单保存到数据库，不依赖RabbitMQ消费者
"""
from database.base import SessionLocal
from models.order_models import Order, OrderItem
from models.goods_models import Goods
from datetime import datetime
import json

def create_manual_order():
    """手动创建订单到数据库"""
    db = SessionLocal()
    
    try:
        # 根据你的截图创建订单
        order_no = "XHS20241113152740853"  # 从截图中看到的订单号
        
        # 检查订单是否已存在
        existing_order = db.query(Order).filter(Order.order_no == order_no).first()
        if existing_order:
            print(f"✅ 订单 {order_no} 已存在")
            return
        
        # 创建订单
        order = Order(
            order_no=order_no,
            user_id=1,  # 假设用户ID为1
            total_amount=4799.00,  # 从截图中看到的金额
            status='pending',
            remark='购物车订单 - 手动创建',
            created_at=datetime.now()
        )
        
        db.add(order)
        db.flush()  # 获取订单ID
        
        # 创建订单项 (假设是iPad Air)
        order_item = OrderItem(
            order_id=order.id,
            goods_id=1,  # 假设商品ID为1
            quantity=1,
            price=4799.00,
            total_price=4799.00
        )
        
        db.add(order_item)
        db.commit()
        
        print(f"✅ 订单 {order_no} 已成功创建到数据库")
        print(f"📊 订单ID: {order.id}")
        print(f"💰 订单金额: ¥{order.total_amount}")
        
    except Exception as e:
        db.rollback()
        print(f"❌ 创建订单失败: {e}")
    finally:
        db.close()

def list_orders():
    """列出所有订单"""
    db = SessionLocal()
    
    try:
        orders = db.query(Order).all()
        
        if orders:
            print(f"📋 数据库中共有 {len(orders)} 个订单:")
            for order in orders:
                print(f"  - 订单号: {order.order_no}")
                print(f"    状态: {order.status}")
                print(f"    金额: ¥{order.total_amount}")
                print(f"    创建时间: {order.created_at}")
                print()
        else:
            print("📋 数据库中没有订单")
            
    except Exception as e:
        print(f"❌ 查询订单失败: {e}")
    finally:
        db.close()

if __name__ == "__main__":
    print("🔧 订单处理工具")
    print("=" * 50)
    
    print("1. 查看当前订单...")
    list_orders()
    
    print("\n2. 创建手动订单...")
    create_manual_order()
    
    print("\n3. 再次查看订单...")
    list_orders()
    
    print("\n💡 完成后请刷新订单页面查看结果")
